/*
 * @Author: Clark
 * @Email: haixuanwoTxh@gmail.com
 * @Date: 2022-03-09 21:30:15
 * @LastEditors: Clark
 * @LastEditTime: 2022-05-14 09:23:22
 * @Description: file content
 */

#ifndef FILE_H
#define FILE_H

#include <string>
#include <unistd.h>

class File
{
public:
    File(std::string fileName)
    {
        this->fileName = fileName;
    }

    bool init()
    {
        if((access(fileName.c_str(), F_OK)) != -1)
        {
             fp = fopen(fileName.c_str(), "r+");
        }
        else
        {
             fp = fopen(fileName.c_str(), "w+");
        }

        if (nullptr == fp)
        {
            return false;
        }
        return true;
    }

    int read_file(uint8_t *buf, size_t bufSize)
    {
        return fread(buf, 1, bufSize, fp);
    }

    int write_file(uint8_t *buf, size_t len)
    {
        return fwrite(buf, 1, len, fp);
    }

    bool fseek_file(long offset)
    {
        int result = fseek(fp, offset, SEEK_SET);
        if (result < 0)
        {
            return false;
        }

        return true;
    }

    bool move_fpos_to_end()
    {
        int result = fseek(fp, 0, SEEK_END);
        if (result < 0)
        {
            return false;
        }

        return true;
    }

    ~File()
    {
        fclose(fp);
    }

private:
    FILE *fp;
    std::string fileName;
};

#endif
